<template>
  <el-card class="mt-10">
    <el-form
      label-width="120px"
      ref="spuFormRef"
      :model="spuFormData"
      :rules="spuFormRules"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input placeholder="SPU名称" v-model="spuFormData.spuName" />
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="请选择" v-model="spuFormData.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in tradeMarkList"
            :key="tm.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input
          type="textarea"
          placeholder="SPU描述"
          v-model="spuFormData.description"
        />
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          v-model:file-list="spuFormData.spuImageList"
          :action="`${BASE__URL}/admin/product/fileUpload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :limit="max"
          accept="image/jpeg, image/png"
          :before-upload="beforeAvatarUpload"
          :on-exceed="handle"
          :on-success="uploadSuccess"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png格式的图片，且小于200kb
            </div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible" width="30%">
          <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select
          :placeholder="`还有${filteredBaseSaleAttrList.length}个未选择`"
          class="mr-10"
          v-model="selectedBaseSaleAttr"
        >
          <el-option
            :label="baseSaleAttr.name"
            :value="`${baseSaleAttr.id}:${baseSaleAttr.name}`"
            v-for="baseSaleAttr in filteredBaseSaleAttrList"
            :key="baseSaleAttr.id"
          />
        </el-select>
        <el-button type="primary" :icon="Plus" @click="addBaseSaleAttr"
          >添加销售属性</el-button
        >
        <el-table :data="spuFormData.spuSaleAttrList" border class="mt-20">
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />
          <el-table-column label="属性名" prop="saleAttrName" />
          <el-table-column label="属性值列表">
            <template v-slot="{ row, $index }">
              <el-tag
                v-for="spuSaleAttrValue in row.spuSaleAttrValueList"
                :key="spuSaleAttrValue.saleAttrValueName"
                class="mx-1"
                closable
                @close="delSpuSaleAttrValue(row, $index)"
                type="success"
              >
                {{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>
              <el-input
                size="small"
                @blur="showButton(row)"
                ref="inputRef"
                v-if="row.isShow"
                v-model="saleAttrValueName"
                @keyup.enter="showButton(row)"
              />
              <el-button
                :icon="Plus"
                size="small"
                @click="showInput(row)"
                v-else
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column>
            <template v-slot="{ row, $index }">
              <el-popconfirm
                :title="`确定删除${row.saleAttrName}吗？`"
                @confirm="delBaseSaleAttr($index)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                    title="删除"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" class="mt-20" @click="addSpuBaseAttr"
          >保存</el-button
        >
        <el-button class="mt-20" @click="showSpuList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "addSpu",
};
</script>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import type { TrademarkList } from "@/api/product/type/trademarkType";
import type {
  spuBaseAttrList,
  spuType,
  spuSaleAttrItem,
  spuSaleAttrValueItem,
} from "@/api/product/type/spuType";
import { ElMessage } from "element-plus";
import { Delete, Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import {
  SpuBaseAttrApi,
  addSpuBaseAttrApi,
  getSpuImageListApi,
  getSpuSaleAttrListApi,
  updateSkuInfoApi,
} from "@/api/product/spu";
import { getAllTrademarkListApi } from "@/api/product/trademark";
import { useCategoryStore } from "@/stores/category";
import { useSpuStore } from "@/stores/spu";
const categoryStore = useCategoryStore();
const spuStore = useSpuStore();
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const tradeMarkList = ref<TrademarkList>([]);
const baseSaleAttrList = ref<spuBaseAttrList>([]);
const BASE__URL = import.meta.env.VITE_API_URL;
const emit = defineEmits(["isShowAddSpu"]);
const showSpuList = () => {
  emit("isShowAddSpu", 1);
};
const selectedBaseSaleAttr = ref("");
const spuFormRef = ref();
// 添加spu属性或修改spu属性
const addSpuBaseAttr = async () => {
  await spuFormRef.value.validate();
  const id = spuStore.spu.id;
  const data = {
    category3Id: categoryStore.category3Id,
    ...spuFormData,
    spuImageList: spuFormData.spuImageList.map((item) => {
      return {
        imgName: item.name,
        imgUrl: (item.response as { data: string }).data,
      };
    }),
  };
  if (id) {
    await updateSkuInfoApi({
      ...data,
      id,
    });
  } else {
    await addSpuBaseAttrApi(data);
  }

  ElMessage.success(`${id ? "修改" : "添加"}spu成功`);
  showSpuList();
};
// form表单数据
const spuFormData = reactive<spuType>({
  spuName: spuStore.spu.spuName,
  tmId: spuStore.spu.tmId,
  description: spuStore.spu.description,
  spuImageList: [],
  spuSaleAttrList: [],
});
const max = 5;
// 超过图片数量限制就隐藏上传框
const isUpdateHidden = computed(() => {
  // console.log(fileList);
  return spuFormData.spuImageList.length < max ? "inline-flex" : "none";
});
// 超出图片数量不允许上传
const handle = () => {
  ElMessage.warning("最大数量不能超过5张");
};
const fileList = ref<UploadUserFile[]>([]);
// 上传图片成功
const uploadSuccess = () => {
  spuFormRef.value.clearValidate(["spuImageList"]);
};
// 自定义校验规则
const spuSaleAttrListValidator = (rule: any, value: any, callback: any) => {
  // rule 检验规则信息，包含规则名称等
  // value 要校验的数据
  // callback 函数 必须调用 用来校验通过用的
  // callback() 校验通过
  // callback(new Error('错误信息')) 表单校验失败，参数是失败信息

  // 销售属性必须有值
  if (!value.length) {
    callback(new Error("至少添加一个销售属性"));
    return;
  }
  // 每个销售属性列表至少有一个销售属性值
  if (
    value.some((item: spuSaleAttrItem) => {
      return !item.spuSaleAttrValueList.length;
    })
  ) {
    callback(new Error("至少添加一个销售值属性"));
    return;
  }
  callback();
};
// 表单验证
const spuFormRules = reactive({
  spuName: [{ required: true, message: "请输入SPU名称", trigger: "blur" }],
  tmId: [{ required: true, message: "请选择SPU品牌", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [{ required: true, message: "请添加SPU图片" }],
  spuSaleAttrList: [{ required: true, validator: spuSaleAttrListValidator }],
});

// 图片上传格式
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const fileTypes = ["image/jpeg", "image/png"];
  if (!fileTypes.includes(rawFile.type)) {
    ElMessage.error("上传文件只能是jpg和png格式");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("文件不能超过200kb");
    return false;
  }
  return true;
};
// 删除图片
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
// 预览图片
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url as string;
  dialogVisible.value = true;
};
// 获取下拉框基础销售属性
onMounted(async () => {
  const res = await SpuBaseAttrApi();
  console.log(res);
  baseSaleAttrList.value = res;
});
// 获取下拉框品牌属性
onMounted(async () => {
  const res = await getAllTrademarkListApi();
  // console.log(res);
  tradeMarkList.value = res;
});
// 修改的时候需要的图片属性
onMounted(async () => {
  const id = spuStore.spu.id;
  if (!id) return;
  const spuImageList = await getSpuImageListApi(id);
  spuFormData.spuImageList = spuImageList.map((item) => {
    return {
      name: item.imgName, // 必填
      url: item.imgUrl, // 图片地址（不填就渲染不了图片）
      response: {
        // 为了将来发送请求，可以得到图片地址
        data: item.imgUrl,
      },
    };
  });
});
// 修改的时候用的销售属性
onMounted(async () => {
  const id = spuStore.spu.id;
  if (!id) return;
  spuFormData.spuSaleAttrList = await getSpuSaleAttrListApi(id);
});
// 添加销售属性
const addBaseSaleAttr = () => {
  if (!selectedBaseSaleAttr.value) return;
  const [id, name] = selectedBaseSaleAttr.value.split(":");
  spuFormData.spuSaleAttrList.push({
    baseSaleAttrId: +id,
    saleAttrName: name,
    spuSaleAttrValueList: [],
  });
  // console.log(spuFormData.spuSaleAttrList);

  selectedBaseSaleAttr.value = "";
};
// 计算添加之后剩余销售属性的值
const filteredBaseSaleAttrList = computed(() => {
  return baseSaleAttrList.value.filter((baseSaleAttr) => {
    if (
      spuFormData.spuSaleAttrList.some((spuSaleAttr) => {
        return spuSaleAttr.baseSaleAttrId === baseSaleAttr.id;
      })
    ) {
      return false;
    }
    return true;
  });
});
// 删除一条属性
const delBaseSaleAttr = (index: number) => {
  spuFormData.spuSaleAttrList.splice(index, 1);
  console.log(spuFormData.spuSaleAttrList);
};
// 销售属性值
const saleAttrValueName = ref("");
// 显示input或button
const inputRef = ref();
const flag = ref(false);
// 显示input
const showInput = async (row: spuSaleAttrItem) => {
  if (flag.value === true) {
    ElMessage.warning("请先完成上一个属性");
    return;
  }
  flag.value = true;
  row.isShow = true;
  await nextTick();
  inputRef.value.focus();
};
// 显示button
const showButton = (row: spuSaleAttrItem) => {
  if (
    row.spuSaleAttrValueList.some((item) => {
      return item.saleAttrValueName === saleAttrValueName.value;
    })
  ) {
    ElMessage.warning("不能添加相同的值");
    return;
  }
  if (!saleAttrValueName.value) {
    return;
  }
  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: saleAttrValueName.value,
  });
  flag.value = false;
  row.isShow = false;
  saleAttrValueName.value = "";
};
// 删除一条属性值
const delSpuSaleAttrValue = (row: spuSaleAttrItem, index: number) => {
  row.spuSaleAttrValueList.splice(index, 1);
};
</script>

<style scoped>
:deep(.el-upload) {
  display: v-bind(isUpdateHidden);
}
</style>
